<template>
  <div style="height: 100vh; display: flex; align-items: center; justify-content: center;">
    <!--顶部横栏-->
    <div style="position: absolute; background-color: #c41335; width: 100%; height: 80px; top: 0; padding-left: 25px;">
      <div style="display: flex; align-items: center; height: 100%; cursor: pointer;" @click="$router.push('/')">
        <img src="@/assets/logo.png" alt="" height="80">
        <span style="margin-left: 20px; color: white; font-size: 25px;">小区消防检查系统</span>
      </div>
    </div>

    <div style="display: flex; justify-content: center; align-items: center; max-width: 800px; width: 100%; border-radius: 6px; box-shadow: 0 0 80px 0 #fac7c7; flex-wrap: wrap; position: relative; top: 80px; margin: 0 20px;">
      <div v-if="!isMobile" style="flex: 1;">
        <img src="@/assets/register.png" alt="" style="width: 100%; height: 400px; object-fit: contain;">
      </div>
      <!--用户名密码-->
      <div
          style="flex: 1; display: flex; align-items: center; justify-content: center; min-width: 280px; padding: 10px 0;">
        <!--box-shadow: 0px 20px 80px 0px indianred;-->
        <el-form :model="registerForm" :rules="rules" ref="userRef" label-width="80px" @keyup.enter.native="register"
                 style="width: 85%">
          <div style="font-size: 20px; font-weight: bold; text-align: center; margin-bottom: 20px">
            欢迎注册
          </div>
          <el-form-item label="用户名" prop="userName">
            <el-input ref="autofocus" prefix-icon="el-icon-user" placeholder="请输入用户名"
                      v-model="registerForm.userName"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input prefix-icon="el-icon-lock" show-password placeholder="请输入密码"
                      v-model="registerForm.password"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPass">
            <el-input prefix-icon="el-icon-lock" show-password placeholder="请确认密码"
                      v-model="registerForm.confirmPass"></el-input>
          </el-form-item>
          <el-form-item label="身份" prop="role">
            <!--选择身份触发数据加载，只加载一次-->
            <el-radio-group v-model="registerForm.role" @input="changeRole">
              <el-radio label="业主" @change.once="loadData"></el-radio>
              <el-radio label="安全检查员" @change.once="loadData"></el-radio>
            </el-radio-group>
          </el-form-item>
          <div>已经有账号？请 <span style="color: blue; cursor: pointer;" @click="$router.push('/login')">登录</span>
          </div>
        </el-form>
      </div>
      <!--业主表单-->
      <div v-if="registerForm.role === '业主'"
           style="flex: 1; display: flex; align-items: center; justify-content: center; min-width: 280px; padding: 10px 0;">
        <!--box-shadow: 0px 20px 80px 0px indianred;-->
        <el-form :model="registerForm" :rules="rules" ref="ownerRef" label-width="80px" @submit.native.prevent
                 style="width: 85%">

          <el-form-item label="真实姓名" prop="name">
            <el-input prefix-icon="el-icon-zhenshixingming" placeholder="请输入真实姓名"
                      v-model="registerForm.name"></el-input>
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input prefix-icon="el-icon-mobile-phone" placeholder="请输入手机号码"
                      v-model="registerForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="邮箱号码" prop="email">
            <el-input prefix-icon="el-icon-mail" placeholder="请输入邮箱"
                      v-model="registerForm.email"></el-input>
          </el-form-item>
          <el-form-item label="拥有房产" prop="selectedHouse">
            <el-cascader clearable filterable :options="houseTree"
                         v-model="registerForm.selectedHouse" placeholder="请选择房产"></el-cascader>
          </el-form-item>
          <div style="display: flex;">
            <el-button type="info" @click="reset" style="flex: 1">重 置</el-button>
            <el-button type="primary" @click="register" style="flex: 1">注 册</el-button>
          </div>
        </el-form>
      </div>
      <!--检查员表单-->
      <div v-if="registerForm.role === '安全检查员'"
           style="flex: 1; display: flex; align-items: center; justify-content: center; min-width: 280px; padding: 10px 0;">
        <el-form :model="registerForm" :rules="rules" ref="inspectorRef" label-width="80px"
                 @keyup.enter.native="register"
                 style="width: 85%">

          <el-form-item label="真实姓名" prop="name">
            <el-input prefix-icon="el-icon-zhenshixingming" placeholder="请输入真实姓名"
                      v-model="registerForm.name"></el-input>
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input prefix-icon="el-icon-mobile-phone" placeholder="请输入手机号码"
                      v-model="registerForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="负责的楼栋" label-width="95px" prop="selectedBuilding">
            <el-select clearable filterable v-model="registerForm.selectedBuilding" placeholder="请选择楼栋">
              <el-option v-for="item in buildings" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
            <!--            <el-cascader clearable :options="buildings"-->
            <!--                         v-model="registerForm.selectedBuilding" placeholder="请选择楼栋"></el-cascader>-->
          </el-form-item>
          <div style="display: flex;">
            <el-button type="info" @click="reset" style="flex: 1">重 置</el-button>
            <el-button type="primary" @click="register" style="flex: 1">注 册</el-button>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>

import {mobileWidth} from "@/utils/mobileWidth";

export default {
  name: 'RegisterView',
  data() {
    var validatePassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请确认密码'))
      } else if (value.toLowerCase() !== this.registerForm.password.toLowerCase()) {
        callback(new Error('密码不一致'))
      } else {
        callback()
      }
    }
    return {
      // 是否开启移动端适配
      isMobile: false,
      // 注册表单数据
      registerForm: {
        userName: '',
        password: '',
        confirmPass: '',
        role: '',
        name: '',
        phone: '',
        email: '',
        selectedHouse: [],
        selectedBuilding: 0,
      },
      //小区房屋数据
      //房屋的树形结构
      houseTree: [],
      buildings: [],
      // 表单验证规则
      rules: {
        userName: [{required: true, message: '请输入用户名', trigger: 'blur'}],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          // {min:6,max:18,message:'密码长度为6到18位',trigger:'blur'}
        ],
        confirmPass: [{validator: validatePassword, required: true, trigger: 'blur'}],
        role: [{required: true, message: '请选择角色', trigger: 'blur'}],
        name: [{required: true, message: '请输入姓名', trigger: 'blur'}],
        phone: [{required: true, message: '请输入手机号', trigger: 'blur'}],
        email: [{required: false, message: '请输入邮箱', trigger: 'blur'}],
        selectedHouse: [{required: true, message: '请选择房产', trigger: 'blur'}],
        selectedBuilding: [{required: true, message: '请选择楼栋', trigger: 'blur'}],
      }
    }
  },
  mounted() {
    this.$refs.autofocus.focus()
    this.isMobile = window.innerWidth < mobileWidth
    // 监听窗口大小变化
    window.addEventListener('resize', () => {
      this.isMobile = window.innerWidth < mobileWidth
    })
  },
  created() {
  },
  methods: {
    //切换角色时清空部分数据
    changeRole() {
      this.registerForm.selectedBuilding = ''
      this.registerForm.selectedHouse = []
      this.registerForm.email = ''
    },
    //加载楼栋或房屋数据
    loadData() {
      if (this.registerForm.role === '业主') {
        this.getHouseTree()
      } else if (this.registerForm.role === '安全检查员') {
        this.getBuildings()
      } else {
        this.$message.error('未知错误')
      }
    },
    //获取房屋的树形结构
    getHouseTree() {
      this.$request.get('/house/house/getHouseTree').then(res => {
        if (res.code === 200) {
          this.houseTree = res.data
        } else {
          this.$message.error('获取房屋信息失败')
        }
      })
    },
    // 获取所有楼栋
    getBuildings() {
      this.$request.get('/house/building/getBuildings').then(res => {
        if (res.code === 200) {
          this.buildings = res.data
        } else {
          this.$message.error('获取楼栋信息失败')
        }
      })
    },
    // handleBuildingChange(buildingId) {
    //   this.buildings.forEach(building => {
    //     if (building.id === buildingId) {
    //       this.registerForm.selectedBuilding = building.name
    //     }
    //   })
    // },
    reset() {
      this.$refs.userRef.resetFields()
      this.$refs.ownerRef.resetFields()
      this.$refs.inspectorRef.resetFields()
    },
    register() {
      let roleRef
      if (this.registerForm.role === '业主') {
        roleRef = 'ownerRef'
      } else if (this.registerForm.role === '安全检查员') {
        roleRef = 'inspectorRef'
      }
      Promise.all([this.$refs.userRef.validate(), this.$refs[roleRef].validate()]).then((valid) => {
        if (valid) {
          this.$request.post('/user/user/register', this.registerForm).then(res => {
            if (res.code === 200) {
              this.$message.success('注册成功，请登录')
              this.$router.push('/login')
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
      // this.$refs['userRef'].validate((valid) => {
      //   if (valid) {
      //     this.$request.post('/user/user/register', this.registerForm).then(res => {
      //       if (res.code === 200) {
      //         this.$message.success('注册成功，请登录')
      //         this.$router.push('/login')
      //       } else {
      //         this.$message.error(res.msg)
      //       }
      //     })
      //   }
      // })
    }
  }
}
</script>

<style scoped>

</style>
